﻿using Neatly.UI;
using UnityEditor;
using UnityEngine;

namespace NeatlyEditor
{
    [CustomEditor(typeof(NSprite), true)]
    [CanEditMultipleObjects]
    public class NSpriteEditor : Editor
    {
        protected SerializedProperty m_SpriteName;
        protected SerializedProperty m_Sprite;
        protected SerializedProperty m_Material;
        protected GUIContent m_SpriteNameContent;
        protected GUIContent m_SpriteContent;
        void OnEnable()
        {
            m_SpriteNameContent = new GUIContent("Sprite Name");
            m_SpriteContent = new GUIContent("Source Image");
            m_Material = serializedObject.FindProperty("m_Material");
            m_SpriteName = serializedObject.FindProperty("m_SpriteName");
            m_Sprite = serializedObject.FindProperty("m_Sprite");
        }
        public override void OnInspectorGUI()
        {
            serializedObject.Update();
            EditorGUILayout.PropertyField(m_SpriteName, m_SpriteNameContent);
            EditorGUILayout.PropertyField(m_Sprite, m_SpriteContent);
            EditorGUILayout.PropertyField(m_Material);
            UseSpritePackerGUI();
            serializedObject.ApplyModifiedProperties();
        }
        private void UseSpritePackerGUI()
        {
            NSprite image = target as NSprite;
            if (!string.IsNullOrEmpty(image.SpriteName) && !image.SpriteName.Equals(m_SpriteName.stringValue))
            {
                ResetSprite(m_SpriteName.stringValue);
            }
            else if (m_Sprite.objectReferenceValue != image.sprite)
            {
                ResetBySprite();
            }
        }
        private void ResetBySprite()
        {
            NSprite image = target as NSprite;
            image.SpriteName = m_Sprite.objectReferenceValue ? m_Sprite.objectReferenceValue.name : "";
            m_SpriteName.stringValue = image.SpriteName;
            ResetSprite(image.SpriteName);
        }
        private void ResetSprite(string spriteName)
        {
            NSprite image = target as NSprite;
            Material material;
            Sprite sprite = UIUtility.FindImageSprite(spriteName, false, out material);
            m_Material.objectReferenceValue = material;
            m_Sprite.objectReferenceValue = sprite;
            image.SetSprite(spriteName, sprite, material);
        }
    }
}